package com.hktf.corelib.utils;

import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.UUID;

public class BuildInfoUtils {

    public static String macAddress() throws SocketException {
        String address = null;
        // 把当前机器上的访问网络接口的存入 Enumeration集合中
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface netWork = interfaces.nextElement();
            // 如果存在硬件地址并可以使用给定的当前权限访问，则返回该硬件地址（通常是 MAC）。
            byte[] by = netWork.getHardwareAddress();
            if (by == null || by.length == 0) {
                continue;
            }
            StringBuilder builder = new StringBuilder();
            for (byte b : by) {
                builder.append(String.format("%02X:", b));
            }
            if (builder.length() > 0) {
                builder.deleteCharAt(builder.length() - 1);
            }
            String mac = builder.toString();
            Log.d("mac", "interfaceName=" + netWork.getName() + ", mac=" + mac);
            // 从路由器上在线设备的MAC地址列表，可以印证设备Wifi的 name 是 wlan0
            if (netWork.getName().equals("wlan0")) {
                Log.d("mac", " interfaceName =" + netWork.getName() + ", mac=" + mac);
                address = mac;
            }
        }
        return address;
    }

    /**
     * 获取设备的mac地址 成功返回MAC地址 失败返回 null
     *
     * @param context
     * @return
     */
    public static String getMAC(Context context) {
        String MacAddress = null;
        try {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                WifiManager manager = (WifiManager)
                        context.getSystemService(Context.WIFI_SERVICE);
                if (manager != null) {
                    MacAddress = manager.getConnectionInfo().getMacAddress();
                }
            } else {
                MacAddress = macAddress();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.P){
            if ("YDS-B80-Android".equals(Config.CLIENTNAME) || "YDS-B80PRO-Android".equals(Config.CLIENTNAME) || "YDS-B80-EN-Android".equals(Config.CLIENTNAME)
                    || "YDS-B80-YOULIBO-Android".equals(Config.CLIENTNAME) || "YDS-B80-BOGELI-Android".equals(Config.CLIENTNAME)) {
                MacAddress=getPADUUID(context);
            }
        }
        return MacAddress;
    }
    public static String getMacAddress() {
        List<NetworkInterface> interfaces = null;
        try {
            interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface networkInterface : interfaces) {
                if (networkInterface != null && TextUtils.isEmpty(networkInterface.getName()) == false) {
                    if ("wlan0".equalsIgnoreCase(networkInterface.getName())) {
                        byte[] macBytes = networkInterface.getHardwareAddress();
                        if (macBytes != null && macBytes.length > 0) {
                            StringBuilder str = new StringBuilder();
                            for (byte b : macBytes) {
                                str.append(String.format("%02X:", b));
                            }
                            if (str.length() > 0) {
                                str.deleteCharAt(str.length() - 1);
                            }
                            return str.toString();
                        }
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return "unknown";
    }

    /**
     * 设备UUID 计算方法 mime + sim 卡串号 + 初始化设备号
     *
     * @param context
     * @return
     */
    public static String getPADUUID(Context context) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
        String tmDevice = null;
        tmDevice = Settings.System.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);

        String tmSerial = "";// sim 卡串号 tm.getSimSerialNumber()

        String androidId = ""
                + android.provider.Settings.Secure.getString(
                context.getContentResolver(),
                android.provider.Settings.Secure.ANDROID_ID);
        UUID deviceUuid = new UUID(androidId.hashCode(),
                ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
        String uniqueId = deviceUuid.toString();

//        uniqueId="ffffffff-c085-af2b-c085-af2b00000000";
        return uniqueId;
    }

    /**
     * 获取到手机型号
     *
     * @return
     */
    public static String getModel() {
        return android.os.Build.MANUFACTURER;// 获取手机型号
    }

    /**
     * 获得android 系统版本
     *
     * @return
     */
    public static String getAndroidVersion() {
        return "Android" + android.os.Build.VERSION.RELEASE;// 获取版本号
    }

    /**
     * 获取android 内核版本
     *
     * @return
     */
    public static String getKernelVersion() {
        String kernelVersion = "";
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream("/proc/version");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return kernelVersion;
        }
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(inputStream), 8 * 1024);
        String info = "";
        String line = "";
        try {
            while ((line = bufferedReader.readLine()) != null) {
                info += line;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bufferedReader.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {
            if (info != "") {
                final String keyword = "version ";
                int index = info.indexOf(keyword);
                line = info.substring(index + keyword.length());
                index = line.indexOf(" ");
                kernelVersion = line.substring(0, index);
            }
        } catch (IndexOutOfBoundsException e) {
            e.printStackTrace();
        }

        return kernelVersion;
    }

    /**
     * 获取屏幕分辨率
     *
     * @return
     */
    public static String getResolution(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        dm = context.getResources().getDisplayMetrics();
        int screenWidth = dm.widthPixels; // 屏幕宽（像素，如：480px）
        int screenHeight = dm.heightPixels; // 屏幕高（像素，如：800px）
        return screenHeight + "*" + screenWidth;
    }

    /**
     * 获取密度
     *
     * @return
     */
    public static String getDpi(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        dm = context.getResources().getDisplayMetrics();
        int densityDPI = dm.densityDpi; // 屏幕密度（每寸像素：120/160/240/320）
        return densityDPI + "";

    }

    /**
     * 获取蓝牙版本号
     *
     * @return
     */
    public static String getBluetoothVersion() {
        return null;

    }

    /**
     * 获取设备版本号
     *
     * @return
     */
    public static String getPadVersion() {
        return android.os.Build.MODEL;
    }
}
